<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.key" placeholder="关键字" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-dropdown v-waves split-button type="primary" class="filter-item" :loading="downloadLoading" @command="handleExport">
        导出
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="select">导出选定</el-dropdown-item>
          <el-dropdown-item command="all">导出全部</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <el-button v-waves :loading="downloadLoading" class="filter-item" type="danger" icon="el-icon-download" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width:100%;"
      @selection-change="handleSelectionChange"
      @sort-change="sortChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" prop="date" sortable="custom" width="150px" align="center" :class-name="getSortClass('date')">
        <template slot-scope="{row}">
          <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span><a :href="row.path" target="_blank">{{ row.path }}</a></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button v-if="row.status!=statusOptions['deleted']" size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :page-sizes="[15, 20, 50, 100]" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { fetchList, deleteMedia, exportMedia } from '@/api/media'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'Media',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      selection: null,
      deleteIds: null,
      listQuery: {
        page: 1,
        limit: 15,
        sort: '-id',
        key: ''
      },
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: {
        'published': 1,
        'draft': 0,
        'deleted': 2
      },
      temp: {
        id: undefined,
        create_time: new Date(),
        name: '',
        path: ''
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
      if (prop === 'date') {
        this.sortByDate(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    sortByDate(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+create_time'
      } else {
        this.listQuery.sort = '-create_time'
      }
      this.handleFilter()
    },
    handleDelete(row, index) {
      const data = {
        id: row.id
      }
      this.$confirm('此操作将删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        deleteMedia(data).then(response => {})
        this.list.splice(index, 1)
      })
    },
    handleBatchDelete() {
      const data = {
        id: this.deleteIds.join(',')
      }
      this.$confirm('此操作将删除所选记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        deleteMedia(data).then(response => {
          this.getList()
        })
      })
    },
    handleExport(command) {
      if (command === 'select') {
        this.handleSelectedExport()
      } else {
        exportMedia().then(response => {
          const link = document.createElement('a')
          const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
          link.style.display = 'none'
          link.href = URL.createObjectURL(blob)
          link.setAttribute('download', `table-data.xlsx`)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        })
      }
    },
    handleSelectedExport() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['id', 'name', 'path', 'create_time']
        const filterVal = ['id', 'name', 'path', 'create_time']
        const data = this.formatJson(filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    handleSelectionChange(val) {
      this.selection = val
      this.deleteIds = []
      val.forEach(item => [
        this.deleteIds.push(item.id)
      ])
    },
    formatJson(filterVal) {
      return this.selection.map(v => filterVal.map(j => {
        if (j === 'create_time') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
